import React, { createContext, useContext, useState, useEffect } from "react";
import TokenManager from "@/utils/token-utils";
import CurrentUserIdManager from "@/utils/user-utils";
import { router } from "expo-router";
import UserProfileStateStore from "@/store/user-profile";
import { DEFAULT_AVATAR_URL } from "@/config/default-value";
import { getUserProfileByTokenApi } from "@/services/api/user";
import { ResponseCode } from "@/types/api-common";

// 定义上下文类型
interface AuthContextType {
  isAuthenticated: boolean;
  isLoading: boolean;
  login: () => void;
  logout: () => void;
  checkAuth: () => Promise<boolean>;
}

// 创建上下文
const AuthContext = createContext<AuthContextType | undefined>(undefined);

// 认证提供者组件
export const AuthProvider = ({ children }: { children: React.ReactNode }) => {
  const [isAuthenticated, setIsAuthenticated] = useState<boolean>(false);
  const [isLoading, setIsLoading] = useState<boolean>(true);
  const setCurrentUserProfile = UserProfileStateStore(
    (state) => state.actions.setCurrentUserProfile
  );
  const currentUser = UserProfileStateStore((state) => state.state.currentUser);

  // 登录方法
  const login = () => {
    setIsAuthenticated(true);
  };

  // 登出方法
  const logout = async () => {
    await TokenManager.clearToken();
    await CurrentUserIdManager.clearUserId();
    setIsAuthenticated(false);
    // 跳转到登录页
    router.replace("/login");
  };

  // 加载用户配置文件
  const loadUserProfile = async (userId: string) => {
    try {
      console.log("正在加载用户配置文件...", userId);

      // 检查 store 中是否已有用户数据
      if (currentUser && currentUser.id === userId) {
        console.log("从 store 中获取用户配置文件");
        console.log(
          "当前 store 中的用户数据:",
          JSON.stringify(currentUser, null, 2)
        );
        // 确保头像有默认值
        const userProfile = {
          ...currentUser,
          avatar: currentUser.avatar || DEFAULT_AVATAR_URL,
        };
        setCurrentUserProfile(userProfile);
        console.log("用户配置文件加载成功:", {
          id: userProfile.id,
          nickname: userProfile.nickname,
          hasAvatar: !!userProfile.avatar,
        });
      } else {
        // 如果 store 中没有数据或 ID 不匹配，从 API 获取
        console.log("从 API 获取用户配置文件");
        const response = await getUserProfileByTokenApi();
        console.log("API返回的配置文件:", response.data.data);

        if (response.data.code === ResponseCode.SUCCESS) {
          const apiProfile = response.data.data;
          console.log("API返回的昵称:", apiProfile.nickname);
          // 确保头像有默认值
          const userProfile = {
            ...apiProfile,
            avatar: apiProfile.avatar || DEFAULT_AVATAR_URL,
            // 如果昵称为空或为User，设置为更有意义的默认值
            nickname: apiProfile.nickname || "新用户",
          };
          setCurrentUserProfile(userProfile);
          console.log("用户配置文件从 API 加载成功:", {
            id: userProfile.id,
            nickname: userProfile.nickname,
            hasAvatar: !!userProfile.avatar,
          });
        } else {
          console.error("API 获取用户配置文件失败");
        }
      }
    } catch (error) {
      console.error("加载用户配置文件失败:", error);
    }
  };

  // 检查认证状态
  const checkAuth = async (): Promise<boolean> => {
    setIsLoading(true);
    try {
      const token = await TokenManager.getToken();
      const isAuth = !!token;
      setIsAuthenticated(isAuth);

      // 如果已认证，加载用户ID和配置文件
      if (isAuth) {
        const userId = await CurrentUserIdManager.loadUserId();
        if (userId) {
          console.log("用户ID已加载:", userId);
          await loadUserProfile(userId);
        } else {
          console.error("用户ID加载失败");
        }
      }

      return isAuth;
    } catch (error) {
      console.error("认证检查失败", error);
      setIsAuthenticated(false);
      return false;
    } finally {
      setIsLoading(false);
    }
  };

  // 组件挂载时检查认证状态
  useEffect(() => {
    checkAuth();
  }, []);

  return (
    <AuthContext.Provider
      value={{
        isAuthenticated,
        isLoading,
        login,
        logout,
        checkAuth,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
};

// 使用认证上下文的Hook
export const useAuth = (): AuthContextType => {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error("useAuth必须在AuthProvider内部使用");
  }
  return context;
};
